package com.glowdayz.glowmee;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.etsy.android.grid.StaggeredGridView;
import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.PouchCMD;

public class BrandPouch extends Activity implements OnScrollListener, AbsListView.OnItemClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	int paramId = 0;
	
	StaggeredGridView mGridView;
    ArrayList<PouchCMD> list = null;
	DataAdapter adapter = null;
	
	// Footer 레이아웃
	LinearLayout llFooter = null;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 10;		// 한 페이지에 보일 수
	private int totalCount = 0;
	
	String url = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_brand_pouch);
		
		am.addActivity(this);
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_paramId", 0);
		String paramTitle = fromIntent.getStringExtra("PARAM_paramTitle");
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText(paramTitle);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setVisibility(View.GONE);
		
		mGridView = (StaggeredGridView) findViewById(R.id.grid_view);
		// 메인 디지안과 별도로 레이아웃을 불러오기
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		// 리스트뷰에 추가
		mGridView.addFooterView(llFooter);
		mGridView.setOnScrollListener(this);
		
		list = new ArrayList<PouchCMD>();
		adapter = new DataAdapter(this, list);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(this);
		
		url = getResources().getString(R.string.server_url) + "/glowmee/listPickXml.do?" +
				"page=" + page + "&count=" + pageSize + "&idBrand=" + paramId;
		
		(new PouchListWorker()).execute();
	}
	
	public class DataAdapter extends ArrayAdapter<PouchCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<PouchCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@SuppressLint("SimpleDateFormat")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_pouch_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			PouchCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				LinearLayout userLayout = (LinearLayout) view.findViewById(R.id.userLayout);
				LinearLayout brandLayout = (LinearLayout) view.findViewById(R.id.brandLayout);
				LinearLayout editerLayout1 = (LinearLayout) view.findViewById(R.id.editerLayout1);
				LinearLayout editerLayout2 = (LinearLayout) view.findViewById(R.id.editerLayout2);
				userLayout.setVisibility(View.GONE);
				brandLayout.setVisibility(View.GONE);
				editerLayout1.setVisibility(View.GONE);
				editerLayout2.setVisibility(View.GONE);
				
				if (item.getIdRegister() == 1 && item.getBrandImage().equals("null")) {
					editerLayout2.setVisibility(View.VISIBLE);
					ImageView pouchImg = (ImageView) view.findViewById(R.id.pouchImg);
					pouchImg.setScaleType(ImageView.ScaleType.FIT_XY);
					ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getImage().trim(), pouchImg);
					return view;
				}
				
				ImageView productImg = (ImageView) view.findViewById(R.id.productImg);
				productImg.setScaleType(ImageView.ScaleType.FIT_XY);
				ImageView userImg = (ImageView) view.findViewById(R.id.userImg);
				userImg.setScaleType(ImageView.ScaleType.FIT_XY);
				ImageView brandImg = (ImageView) view.findViewById(R.id.brandImg);
				brandImg.setScaleType(ImageView.ScaleType.FIT_XY);
				
				ImageView categoryImg = (ImageView) view.findViewById(R.id.pouchCategory);
				TextView productCount = (TextView) view.findViewById(R.id.productCount);
				TextView pouchTitle = (TextView) view.findViewById(R.id.pouchTitle);
				TextView pouchText = (TextView) view.findViewById(R.id.pouchText);
				TextView recommentCount = (TextView) view.findViewById(R.id.recommentCount);
				TextView commentCount = (TextView) view.findViewById(R.id.commentCount);
				TextView date = (TextView) view.findViewById(R.id.date);
				TextView nickName = (TextView) view.findViewById(R.id.nickName);
				TextView userInfo = (TextView) view.findViewById(R.id.userInfo);
				
				if (item.getIdPouchCategoryValue().equals("이거샀어")) {
					categoryImg.setImageResource(R.drawable.pick_cate1);
				} else if (item.getIdPouchCategoryValue().equals("이거어때")) {
					categoryImg.setImageResource(R.drawable.pick_cate2);
				} else if (item.getIdPouchCategoryValue().equals("이거추천")) {
					categoryImg.setImageResource(R.drawable.pick_cate3);
				} else if (item.getIdPouchCategoryValue().equals("사고싶어")) {
					categoryImg.setImageResource(R.drawable.pick_cate4);
				} else if (item.getIdPouchCategoryValue().equals("아무거나")) {
					categoryImg.setImageResource(R.drawable.pick_cate5);
				}
				
				productCount.setText(item.getProductCount() + " picks");
				pouchTitle.setText(item.getPouchTitle());
				pouchText.setText(item.getPouchText());
				recommentCount.setText(String.valueOf(item.getRecommendCount()));
				commentCount.setText(String.valueOf(item.getCommentCount()));
				date.setText(item.getCreate_date());
				
				try {
					Date dateTime = (new SimpleDateFormat("yyyyMMddHHmmss")).parse(item.getCreate_date().trim());
					String time = DateTime.getInstance().calculateTime(dateTime);
					if (time == null) {
						date.setText(DateTime.getInstance().getDateTimeString3(item.getCreate_date().trim()));
					} else {
						date.setText(time);
					}
					date.setTextSize(11);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getImage().trim(), productImg);
				
				if (item.getUserType().equals("ADMIN")){
					editerLayout1.setVisibility(View.VISIBLE);
					brandLayout.setVisibility(View.VISIBLE);
					
					if (!item.getBrandImage().equals("null")){
						ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getBrandImage().trim(), brandImg);
					} else {
						brandImg.setImageResource(R.drawable.empty_logo);
					}
					return view;
				}
				
				if (item.getUserType().equals("USER")) {
					editerLayout1.setVisibility(View.VISIBLE);
					userLayout.setVisibility(View.VISIBLE);
					
					nickName.setText(item.getIdRegisterValue());
					String info = null;
					if (item.getBirthYear() > 0) {
						int age = Calendar.getInstance().get(Calendar.YEAR) - item.getBirthYear() + 1;
						info = age + "세";
					}
					if (!item.getSkinType().equals("null")) {
						if (info == null) {
							info = item.getSkinType();
						} else {
							info += "," + item.getSkinType();
						}
					}
					userInfo.setText(info);
					
					if (item.getBm() == null) {
						userImg.setImageResource(R.drawable.profileimg);
					} else {
						userImg.setImageBitmap(item.getBm());
					}
					return view;
				}
			}
			return view;
		}
	}
	
	public class PouchListWorker extends AsyncTask<Object, PouchCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idPouch = 0;
				String idPouchCategoryValue = null;
				int idBrand = 0;
				String idBrandValue = null;
				String pouchTitle = null;
				String pouchText = null;
				int editerPick = 0;
				String create_date = null;
				int idRegister = 0;
				String idRegisterValue = null;
				String userType = null;
				int birthYear = 0;
				String skinType = null;
				int productCount = 0;
				int recommendCount = 0;
				int commentCount = 0;
				String thumbnail = null;
				String user_thumbnail = null;
				String brand_thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idPouch")) {
							parser.next();
							idPouch = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idPouchCategoryValue")) {
							parser.next();
							idPouchCategoryValue = parser.getText();
						} else if (tag.equals("idBrand")) {
							parser.next();
							idBrand = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idBrandValue")) {
							parser.next();
							idBrandValue = parser.getText();
						} else if (tag.equals("pouchTitle")) {
							parser.next();
							pouchTitle = parser.getText();
						} else if (tag.equals("pouchText")) {
							parser.next();
							pouchText = parser.getText();
						} else if (tag.equals("editerPick")) {
							parser.next();
							editerPick = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("idRegister")) {
							parser.next();
							idRegister = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idRegisterValue")) {
							parser.next();
							idRegisterValue = parser.getText();
						} else if (tag.equals("userType")) {
							parser.next();
							userType = parser.getText();
						} else if (tag.equals("birthYear")) {
							parser.next();
							birthYear = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("skinType")) {
							parser.next();
							skinType = parser.getText();
						} else if (tag.equals("productCount")) {
							parser.next();
							productCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("recommendCount")) {
							parser.next();
							recommendCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("commentCount")) {
							parser.next();
							commentCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						} else if (tag.equals("user_thumbnail")) {
							parser.next();
							user_thumbnail = parser.getText();
						} else if (tag.equals("brand_thumbnail")) {
							parser.next();
							brand_thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							
							Bitmap bm = null;
							if (user_thumbnail != null) {
								try {
									URL url2 = new URL(getResources().getString(R.string.server_url) + user_thumbnail.trim()); 
									URLConnection conn = url2.openConnection(); 
									conn.connect(); 
									BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
									bm = BitmapFactory.decodeStream(bis); 
									bis.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							
							PouchCMD item = new PouchCMD(idPouch, idRegister, idRegisterValue, userType, idPouchCategoryValue, 
									pouchTitle, pouchText, recommendCount, editerPick, create_date, thumbnail, user_thumbnail, brand_thumbnail, 
									productCount, commentCount, idBrand, idBrandValue, birthYear, skinType, bm);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(PouchCMD... param) {
			adapter.add(param[0]);
		}

		@Override
		protected void onPostExecute(Object param) {
			llFooter.setVisibility(View.GONE);
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(BrandPouch.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new PouchListWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				url = getResources().getString(R.string.server_url) + "/glowmee/listPickXml.do?" +
						"page=" + page + "&count=" + pageSize + "&idBrand=" + paramId;
				(new PouchListWorker()).execute();
			}
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		PouchCMD select = adapter.getItem(arg2);
		Intent intent = new Intent(BrandPouch.this, ViewPouch.class);
		intent.putExtra("PARAM_paramId", select.getIdPouch());
		startActivity(intent);
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
